package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper();

        lambdaQueryWrapper.eq(dto.getStatus() != null, ApUserRealname::getStatus, dto.getStatus());

        IPage<ApUserRealname> resultPage = page(page, lambdaQueryWrapper);

        // 3 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                resultPage.getTotal(), resultPage.getRecords());
    }

    @Resource
    private ApUserMapper apUserMapper;

    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 300000)
    //@Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {

        if(dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证【id】不能为空");
        }

        // 根据实名认证信息的id查询实名认证记录
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if(apUserRealname == null)
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证记录中查无此人");
        // 判断实名认证的状态是否为待审核状态
        if(!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){ // 实名认证不是待审核状态
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证的状态为非审核状态");
        }

        // 根据实名认证记录的用户id查询用户信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证关联的用户信息不存在");
        }

        // 修改状态
        apUserRealname.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg()); // 驳回的原因
        }
        this.updateById(apUserRealname);

        if(AdminConstants.FAIL_AUTH.equals(status)){ // 已经处于失败状态，到此结束
            return ResponseResult.okResult();
        }

        // 如果是9，代表审核通过，
        // 1. 开通自媒体账户
        WmUser wmUser = createWmAuthor(apUser);
        // 2. 创建作者信息（查询作者信息是否已经创建，保存作者信息）
        createApAuthor(apUser, wmUser);
        return ResponseResult.okResult();
    }

    @Resource
    private ArticleFeign articleFeign;

    /**
     * 远程调用article微服务，创建 AP 作者
     *
     * @param apUser         AP 用户
     * @param wmUser AP 用户实名
     */
    private void createApAuthor(ApUser apUser, WmUser wmUser) {
        // 1. 根据用户id查询作者信息是否存在
        ResponseResult<ApAuthor> articleFeignByUserId = articleFeign.findByUserId(apUser.getId());
        if(!articleFeignByUserId.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, articleFeignByUserId.getErrorMessage());
        }

        // 2. 若作者存在，抛出异常并提示已存在
        ApAuthor apAuthor = articleFeignByUserId.getData();


        if(apAuthor != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "作者信息已存在");
        }
        // 3. 若作者不存在，创建作者信息，并远程保存
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult saveApAuthorResult = articleFeign.save(apAuthor);
        if (!saveApAuthorResult.checkCode()) { // 远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, saveApAuthorResult.getErrorMessage());
        }

        // 不过demo时间的贵哦成中，并不是一件简单地事情
    }

    @Resource
    private WemediaFeign wemediaFeign;

    /**
     * 开通自媒体用户
     *
     * @param apUser AP 用户
     * @return <p>
     */
    private WmUser createWmAuthor(ApUser apUser) {
        // 1. 远程根据用户名，查询自媒体用户信息
        ResponseResult<WmUser> responseResult = wemediaFeign.findByName(apUser.getName());
         // 远程调用是否成功 responseResult.checkCode() == true
        if(!responseResult.checkCode()){ // 远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, responseResult.getErrorMessage());
        }
        WmUser wmUser = responseResult.getData();
        // 2. 若已存在用户名对应的自媒体用户，则直接抛异常，结束方法
        if(wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "自媒体账户已存在");

        }
        // 3. 不存在用户名对应的自媒体用户，创建与用户名关联的自媒体用户
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());

        ResponseResult<WmUser> wmUserSaveResult = wemediaFeign.save(wmUser);
        if(!wmUserSaveResult.checkCode()){ // 远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, wmUserSaveResult.getErrorMessage());
        }
        return wmUserSaveResult.getData();
    }
}